const Service = require('egg').Service

class contactWayService extends Service {
  get ContactWayModel() {
    return this.ctx.model.ContactWay
  }
  // 插入标签
  async insert(data) {
    const _data = await new this.ContactWayModel(data)
    _data.save()
    return _data
  }


  // 删除
  async delete(id) {
    const { ctx } = this
    const _data = await this.ContactWayModel.findById(id)
    if(!_data) {
      ctx.throw(422,'_id不正确！')
    }
    _data.remove()
    return {
      code: 200,
      message: '删除成功'
    }
  }

  // 修改
  async update(body) {
    return await this.ContactWayModel.findByIdAndUpdate(body.id,Object.assign(body,{updatedAt: Date.now()})) 
  }

  // 查询标签
  async list(body) {
    const pageNum = Number.parseInt(body.pageNum || 1)
    const pageSize = Number.parseInt(body.pageSize || 10)
    const titleReg = new RegExp(body.title,'ig')
    const ret = await this.ContactWayModel.find({
      title: titleReg
    },null,{
      sort: {sortNum: -1}
    }).skip((pageNum-1)*pageSize).limit(pageSize)
    const total = await this.ContactWayModel.countDocuments({
      title: titleReg
    })
    return {
      list: ret,
      total
    }
  }
}

module.exports = contactWayService